$( document ).ready(function() {
  $('[class^="ajax_shipper_"]').blur(function(){
        shipperItemLoad($(this));
  });
  $('[class^="ajax_area_"]').blur(function(){
        areaItemLoad($(this));
  });
  $('body').click(function() {
	//   $('#overlay').hide();
	});
  $('[class^="ajax_shipping_fee_"]').blur(function(){
        shippingFeeItemLoad($(this));
  });

  $('[class^="ajax_kanri_"]').blur(function(){
        kanriItemLoad($(this));
  });

  $('[class^="ajax_sdiff_"]').blur(function(){
        shipperDiffItemLoad($(this));
  });

  $('[class^="ajax_product_diff_"]').blur(function(){
        productDiffItemLoad($(this));
  });

  $('#exportExcel').click(function(){
        shippingFeeExcel();
  });
  
  //$('#imagePdfExport').click(function(){
        //imagePdfExport();
  //}); 
  
  $('#cboShipper').change(function(){
         $oldHref = $('#shipping_store_list_preview').attr('link-fix');
         $subParam = 'dateFrom=' + $('#datepicker1').val() + '&dateTo=' + $('#datepicker2').val();
  		 $newHref = $oldHref + '?SEQ=' + $(this).val() + '&' + $subParam;
  		 $('#shipping_store_list_preview').attr('href', $newHref);
  });  
  
  $('#cboShipper').change(function(){
         $oldHref = $('#shipping_fee_list_preview').attr('link-fix');
         $subParam = 'dateFrom=' + $('#datepicker1').val() + '&dateTo=' + $('#datepicker2').val();
  		 $newHref = $oldHref + '?SEQ=' + $(this).val() + '&' + $subParam;
  		 $('#shipping_fee_list_preview').attr('href', $newHref);
  });  
    
  $('#idRestore').click(function(){
		restoreDB();
  });    
  $('#idBackup').click(function(){
		backupDB();
  });     
  
});

function restoreDB() {
	r = confirm("現マスターは、なくなりますが・・よろしいですね？");
	if (r == false) {
		return;
	}
	 $("#overlay").show();
	 $.ajax({
          type: "POST",
          url: '/ajax/restore',
          // dataType: "json",
          success: function(msg) {
          	
              $("#overlay").hide();
              if (msg != '1') {
                  alert('Error:' + msg);
              } else {
              	  alert('正常に終了しました');
              }
          }
        });
}

function backupDB() {
	 $("#overlay").show();
	 $.ajax({
          type: "POST",
          url: '/ajax/backup',
          // dataType: "json",
          success: function(msg) {
          	
              $("#overlay").hide();
              if (msg != '1') {
                  alert('Error:' + msg);
              } else {
              	  alert('マスタBACKUP完了');
              }
          }
        });
}

// products diff

function productDiffItemLoad ($obj) {
      id = ($obj.attr('class')).replace('ajax_product_diff_', '');
      // check validate field here TODO
      productDiffChange(id,$obj.val(), $obj.attr('data-url'), $obj.attr('data-field'));
}
// shipper change
function shipperItemLoad ($obj) {
      id = ($obj.attr('class')).replace('ajax_shipper_', '');
      // check validate field here TODO
      shiperChange(id,$obj.val(), $obj.attr('data-url'), $obj.attr('data-field'));
}

function shipperDiffItemLoad ($obj) {
      id = ($obj.attr('class')).replace('ajax_sdiff_', '');
      // check validate field here TODO
      shiperDiffChange(id,$obj.val(), $obj.attr('data-url'), $obj.attr('data-field'));
}

function kanriItemLoad ($obj) {
      id = ($obj.attr('class')).replace('ajax_kanri_', '');
      // check validate field here TODO
      kanriChange(id,$obj.val(), $obj.attr('data-url'), $obj.attr('data-field'));
}


function shippingFeeItemLoad ($obj) {
      id = ($obj.attr('class')).replace('ajax_shipping_fee_', '');
      // check validate field here TODO
      shippingFeeChange(id,$obj.val(), $obj.attr('data-url'), $obj.attr('data-field'));
}

// shipping fee excel
function shippingFeeExcel(){
    $.ajax({
          type: "POST",
          url: '/ajax/shippingExcel',
          dataType: "json",
          // data: 'id=' + id + "&value="  + val + '&field=' + field,
          success: function(msg) {
              if (msg['status'] == '0') {
                  alert('Update failed');
              } else {
              	  alert('Export successfully!');
              }
          }
        });

}

// imagePdfExport
function imagePdfExport(){
	// show waiting button
    $.ajax({
          type: "POST",
          url: '/ajax/frmDataImagePdf',
          dataType: "json",
          data: 'dateFrom=' + $('#datepicker1').val() + "&dateTo="  + $('#datepicker2').val(),
          success: function(msg) {
          	  // hide waiting button
              if (msg != '1') {
                  alert(msg);
              } else {
              	  alert('データ作成完了');
              }
          }
        });

}


function ajax_ftp_retrieve() {
    $.ajax({
          type: "POST",
          url: '/ftp',
          success: function(msg) {
              if (msg == 1) {
                  alert('Transfer done successfully!');
              }　else {
                  alert('Transfer failed, please check something and try again!');
                 }
          }
        });
}

function areaItemLoad ($obj) {
      id = ($obj.attr('class')).replace('ajax_area_', '');
      // check validate field here TODO
      areaChange(id,$obj.val(), $obj.attr('data-url'), $obj.attr('data-field'));
}

// kanri
function kanriChange(id, val, url, field){
    $.ajax({
          type: "POST",
          url: url,
          dataType: "json",
          data: 'id=' + id + "&value="  + val + '&field=' + field,
          success: function(msg) {
              if (msg['status'] == '0') {
                  alert('Update failed');
              }
          }
        });

}

// shipper diff

function shiperDiffChange(id, val, url, field){
    $newRecHtml = $('#newRec').html();
    $.ajax({
          type: "POST",
          url: url,
          dataType: "json",
          data: 'id=' + id + "&value="  + val + '&field=' + field,
          success: function(msg) {
              if (msg['status'] == '0') {
                  alert('Update failed');
              } else {
                  // save sucessfully
                  if (msg['mode'] == 'insert') {
                      // update class name with new id
                      $('.ajax_sdiff_insert').removeClass('ajax_sdiff_insert')
                                               .addClass('ajax_sdiff_' + msg['id']);
                      // set id new row to old row after insert successfully
                      $('#newRec').removeAttr('id');
                      // insert new row with insert
                      $('#tblShipperDiff').append('<tr id=\'newRec\'>' + $newRecHtml + '</tr>');
                      // refresh grid after change
                    $('[class^="ajax_sdiff_insert"]').blur(function(){
                          shipperDiffItemLoad($(this));
                    });
                  }
              }
          }
        });

}

// product diff change

function productDiffChange(id, val, url, field){
    $newRecHtml = $('#newRec').html();
    $.ajax({
          type: "POST",
          url: url,
          dataType: "json",
          data: 'id=' + id + "&value="  + val + '&field=' + field,
          success: function(msg) {
              if (msg['status'] == '0') {
                  alert('Update failed');
              } else {
                  // save sucessfully
                  if (msg['mode'] == 'insert') {
                      // update class name with new id
                      $('.ajax_product_diff_insert').removeClass('ajax_product_diff_insert')
                                               .addClass('ajax_product_diff_' + msg['id']);
                      // set id new row to old row after insert successfully
                      $('#newRec').removeAttr('id');
                      // insert new row with insert
                      $('#tblProduct').append('<tr id=\'newRec\'>' + $newRecHtml + '</tr>');
                      // refresh grid after change
                    $('[class^="ajax_product_diff_insert"]').blur(function(){
                          productDiffItemLoad($(this));
                    });
                  }
              }
          }
        });

}

// shipper
function shiperChange(id, val, url, field){
    $newRecHtml = $('#newRec').html();
    $.ajax({
          type: "POST",
          url: url,
          dataType: "json",
          data: 'id=' + id + "&value="  + val + '&field=' + field,
          success: function(msg) {
              if (msg['status'] == '0') {
                  alert('Update failed');
              } else {
                  // save sucessfully
                  if (msg['mode'] == 'insert') {
                      // update class name with new id
                      $('.ajax_shipper_insert').removeClass('ajax_shipper_insert')
                                               .addClass('ajax_shipper_' + msg['id']);
                      // set id new row to old row after insert successfully
                      $('#newRec').removeAttr('id');
                      // insert new row with insert
                      $('#tblShipper').append('<tr id=\'newRec\'>' + $newRecHtml + '</tr>');
                      // refresh grid after change
                    $('[class^="ajax_shipper_insert"]').blur(function(){
                          shipperItemLoad($(this));
                    });
                  }
              }
          }
        });

}

// area
function areaChange(id, val, url, field){
    $newRecHtml = $('#newRec').html();
    $.ajax({
          type: "POST",
          url: url,
          dataType: "json",
          data: 'id=' + id + "&value="  + val + '&field=' + field,
          success: function(msg) {
              if (msg['status'] == '0') {
                  alert('Update failed');
              } else {
                  // save sucessfully
                  if (msg['mode'] == 'insert') {
                      // update class name with new id
                      $('.ajax_area_insert').removeClass('ajax_area_insert')
                                               .addClass('ajax_area_' + msg['id']);
                      // set id new row to old row after insert successfully
                      $('#newRec').removeAttr('id');
                      // insert new row with insert
                      $('#tblArea').append('<tr id=\'newRec\'>' + $newRecHtml + '</tr>');
                      // refresh grid after change
                    $('[class^="ajax_area_insert"]').blur(function(){
                          areaItemLoad($(this));
                    });
                  }
              }
          }
        });

}

// shipping_fee
function shippingFeeChange(id, val, url, field){
    $newRecHtml = $('#newRec').html();
    $.ajax({
          type: "POST",
          url: url,
          dataType: "json",
          data: 'id=' + id + "&value="  + val + '&field=' + field,
          success: function(msg) {
              if (msg['status'] == '0') {
                  alert('Update failed');
              } else {
                  // save sucessfully
                  if (msg['mode'] == 'insert') {
                      // update class name with new id
                      $('.ajax_shipping_fee_insert').removeClass('ajax_shipping_fee_insert')
                                               .addClass('ajax_shipping_fee_' + msg['id']);
                      // set id new row to old row after insert successfully
                      $('#newRec').removeAttr('id');
                      // insert new row with insert
                      $('#tblShippingFee').append('<tr id=\'newRec\'>' + $newRecHtml + '</tr>');
                      // refresh grid after change
                    $('[class^="ajax_shipping_fee_insert"]').blur(function(){
                          shippingFeeItemLoad($(this));
                    });
                  }
              }
          }
        });

}

// print directly from html
function printDiv(divID)
    {
           var sOption="toolbar=no,location=no,directories=yes,menubar=no,";
               sOption+="scrollbars=yes,width=775,height=600,left=10,top=25";


           var sWinHTML = $('#' + divID).html();


           var winprint=window.open("","",sOption);
               winprint.document.open();
               winprint.document.write('<html>');
               winprint.document.write('<body><div id=print>');
               winprint.document.write('<input id=noprint type="button" value="Print Page" onclick="window.focus();window.print();return false;" />');
               winprint.document.write('<br/><br/>');
               winprint.document.write(sWinHTML);
               winprint.document.write('               ');
               winprint.document.write('</div></body></html>')
               winprint.document.close();
               winprint.focus();
}

function importData(){
    // set waiting status for layout
    $('#overlay').show();
    $.ajax({
          type: "POST",
          url: '/import',
          success: function(msg) {
          	$('#overlay').hide();
              if (msg != '1') {
                  alert(msg);
              } else {
                  alert('取込終了');
              }
          }
        });

}